package servlet;

import dao.NewDao;
import dao.UserDao;
import entity.User;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/editor.do")
@MultipartConfig
public class RichEditorServlet extends HttpServlet {

    private static final long serialVersionUID = 2L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        String title = request.getParameter("inputTitle");
        System.out.println(title);
        String html = request.getParameter("html");
        if (html != null) {
            //获取作者名
            User user = (User) request.getSession().getAttribute("user");
            String author = user.getUserName();
            System.out.println(author);
            String cover = getFirstImageSrc(html);
            System.out.println(cover);
            NewDao newDao = new NewDao();
            int ret = newDao.newsUpload(title,cover,author,html);
            if(ret == -1) {
                request.getRequestDispatcher("error.jsp").forward(request, response);
            }
            response.getWriter().print("<html><head><meta charset=\"UTF-8\"></head><body>"
            + html
            + "</body></html>");
        }
    }

    public static String getFirstImageSrc(String html) {
        Pattern pattern = Pattern.compile("<img[^>]*src=\"([^\"]*)\"");
        Matcher matcher = pattern.matcher(html);
        if (matcher.find()) {
            return matcher.group(1);
        } else {
            return null;
        }
    }
    
}

